import Hotkeywords from "./Hotkeywords";
import searchicon from "../../../../imgs/searchicon.png";
import EventEmitterUtils from "../../common/utils/EventEmitterUtils";
import EventApi from "@module/EventApi";

function HintList(props) {
    const [currentState, updateState] = usePartState({ hoverIndex: 0 });
    const { whenClick, whenOver, currentScope, dataList } = props;
    const clickHint = (item, index) => {
        // updateState({ hideHint: true });
        whenClick.call(currentScope, item, index);
    };

    const overHint = (item, index) => {
        whenOver.call(currentScope, item, index);
    };

    function hideHint(e) {
        if (!e || e.target.id != "HintList-id") {
            EventApi.emit("hideHint", false);
        }
    }

    React.useEffect(() => {
        window.addEventListener("click", hideHint);
        return () => {
            window.removeEventListener("click", hideHint);
        };
    });

    React.useEffect(() => {
        EventApi.on("autoCompleteKey", function(data) {
            let dataList = props.currentScope.state.autoHintResult;
            if (data == 38) {
                // 向上
                if (currentState.hoverIndex > 0) {
                    currentState.hoverIndex -= 1;
                }
            } else if (data == 40) {
                if (currentState.hoverIndex < dataList.length - 1) {
                    currentState.hoverIndex += 1;
                }
            }
            updateState(currentState);
            let index = currentState.hoverIndex;
            let item = dataList[index];
            overHint(item, index);
        });
    }, []);

    // React.useEffect(() => {
    //     updateState({ hideHint: false });
    // },dataList);

    /*const dataList = [
        "EWSR1",
        "EW 7197",
        "EW-7197",
        "EWS Antibody",
        "EWSR1 Antibody"
    ];*/
    let warpStyle = {
        width: "521px",
        outline: "medium",
        borderRadius: "0px 0px 4px 4px",
        border: "2px solid rgba(0, 147, 235, 1)",
        borderTop: "none",
        boxSizing: "border-box",

        position: "absolute",
        top: "40px",
        zIndex: 999,
        backgroundColor: "white",
        left: "0px"
    };
    let lineStyle = {
        lineHeight: "36px",
        cursor: "pointer",
        fontSize: "12px",
        paddingLeft: "36px"
    };
    if (!dataList.length || currentState.hideHint) {
        return null;
    }

    return (
        <div id="HintList-id" className="HintList-wrap" style={warpStyle}>
            {dataList &&
                dataList.map(function(item, index) {
                    return (
                        <div
                            key={item}
                            className={Uts.sc([
                                "HintList-list",
                                currentState.hoverIndex == index
                                    ? "HintList-list-active"
                                    : ""
                            ])}
                            style={lineStyle}
                            onClick={() => {
                                clickHint(item, index);
                            }}
                            // onMouseOver={()=>{
                            //     overHint(item, index)
                            // }}
                        >
                            {item}
                        </div>
                    );
                })}
        </div>
    );
}

export default class SearchComp extends React.Component {
    constructor(props) {
        super(props);
        const { searchTab } = this.props;
        this.state = {
            tab_select_index: searchTab ? searchTab : 0,
            autoHintResult: []
        };
        this.placeholder = {
            "0": "搜索商品名/货号/CAS号/品牌",
            "1": "搜索供应商"
        };
        this.searchText = "";
    }

    doSearch(tab_select_index) {
        EventApi.emit("hideHint", false);
        if (tab_select_index == 1 && this.searchText) {
            $state.go({
                stateName: "/searchResults",
                params: { supp: this.searchText }
            });
            return;
        }
        if (this.searchText) {
            $state.go({
                stateName: "/searchProduct",
                params: { key: this.searchText }
            });
        }
    }

    changeSearch(data) {
        // console.log("changeSearch", data);
        this.searchText = data.key;
        document.getElementById("searchProductId").value = data.key;
    }

    componentDidMount() {
        let _self = this;
        EventApi.on("searchItemClick", this.changeSearch.bind(this));
        EventApi.on("hideHint", function() {
            _self.handAutoTextSearch();
        });
    }

    handAutoTextSearch(value) {
        let url = "/search/input";
        let _self = this;
        if (!value) {
            _self.setState({ autoHintResult: [] });
            return false;
        }
        REST.post(url, { query: value, size: 5 }, "noInfo").then(
            function(data) {
                //{"keywordList":["EWSR1","EW 7197","EW-7197","EWS Antibody","EWSR1 Antibody"]}
                if (data && data.keywordList) {
                    _self.setState({ autoHintResult: data.keywordList });
                }
            },
            function(error) {
                //console.log(error);
            }
        );
        // console.log(_self.state.autoHintResult)
    }

    handleHintClick(value, index) {
        if (!value) {
            return false;
        }
        this.changeSearch({ key: value });
        if ($state.params && value != $state.params.key) {
            this.doSearch(this.state.tab_select_index);
            this.setState({ autoHintResult: [] });
        }
    }

    handleHintOver(value, index) {
        if (!value) {
            return false;
        }
        this.changeSearch({ key: value });
        // if ($state.params && value != $state.params.key) {
        //     // this.doSearch(this.state.tab_select_index);
        //     this.setState({ autoHintResult: [] });
        // }
    }

    componentWillUnmount() {
        EventApi.off("searchItemClick", this.changeSearch);
    }

    render() {
        const { tab_select_index } = this.state;
        global.tab_select_index = tab_select_index;
        const {
            isInSupp,
            clickHighLevel,
            showHighLevel,
            hideHighLevel
        } = this.props;
        return (
            <div
                className={
                    isInSupp ? "search-comps-box-insupp" : "search-comps-box"
                }
            >
                <div className={"search-input-warpper"}>
                    <div
                        style={{
                            display: "flex",
                            position: "relative"
                        }}
                    >
                        <img
                            src={searchicon}
                            className={"search-input-search-icon"}
                        />
                        <input
                            type="text"
                            id="searchProductId"
                            className={Uts.sc([
                                "search-detail-searchcomp",
                                this.state.autoHintResult &&
                                this.state.autoHintResult.length
                                    ? "input-no-border-bottom"
                                    : ""
                            ])}
                            style={{ width: isInSupp ? 446 : null }}
                            placeholder={this.placeholder[tab_select_index]}
                            onChange={e => {
                                this.searchText = e.target.value;
                                if (
                                    this.searchText &&
                                    this.searchText.length <= 15
                                ) {
                                    this.handAutoTextSearch(e.target.value);
                                }
                            }}
                            onKeyUp={e => {
                                if (e.keyCode === 13) {
                                    this.doSearch(tab_select_index);
                                } else if (e.keyCode === 38) {
                                    //向上

                                    EventApi.emit("autoCompleteKey", 38);
                                } else if (e.keyCode === 40) {
                                    //向下
                                    EventApi.emit("autoCompleteKey", 40);
                                }
                            }}
                        />
                        <HintList
                            whenClick={this.handleHintClick}
                            whenOver={this.handleHintOver}
                            currentScope={this}
                            dataList={this.state.autoHintResult}
                        />
                        {isInSupp ? (
                            <div
                                onClick={() => {
                                    $state.go({
                                        stateName: "/searchProduct",
                                        params: { key: this.searchText }
                                    });
                                }}
                                className={"search-input-comp-global"}
                            >
                                <p style={{ color: "#fff", fontSize: 14 }}>
                                    搜全站
                                </p>
                            </div>
                        ) : (
                            <div
                                onClick={() => {
                                    this.doSearch(tab_select_index);
                                }}
                                className={"search-input-comp"}
                            >
                                <p style={{ color: "#fff", fontSize: 14 }}>
                                    搜索
                                </p>
                            </div>
                        )}
                    </div>
                </div>
                {isInSupp ? null : (
                    <div className={"search-comps-tabs"}>
                        <div
                            onClick={() => {
                                this.setState({
                                    tab_select_index: 0
                                });
                            }}
                            className={
                                tab_select_index == 0
                                    ? "search-comps-tab-item-select"
                                    : "search-comps-tab-item"
                            }
                        >
                            <p
                                className={
                                    tab_select_index == 0
                                        ? "search-comps-tab-p-select"
                                        : "search-comps-tab-p"
                                }
                            >
                                商品
                            </p>
                        </div>
                        <div
                            onClick={() => {
                                this.setState({
                                    tab_select_index: 1
                                });
                            }}
                            className={
                                tab_select_index == 1
                                    ? "search-comps-tab-item-2-select"
                                    : "search-comps-tab-item-2"
                            }
                        >
                            <p
                                className={
                                    tab_select_index == 1
                                        ? "search-comps-tab-p-select"
                                        : "search-comps-tab-p"
                                }
                            >
                                供应商
                            </p>
                        </div>
                    </div>
                )}

                {this.renderRightText()}

                <Hotkeywords />
            </div>
        );
    }

    renderRightText() {
        const {
            isInSupp,
            clickHighLevel,
            showHighLevel,
            hideHighLevel
        } = this.props;
        if (!global.hasLogin) {
            return null;
        }
        if (isInSupp) {
            return (
                <div
                    onClick={() => {
                        let params = $state.params;
                        let suppId = params.suppId;
                        $state.go({
                            stateName: "/searchProduct",
                            params: {
                                key: this.searchText,
                                suppId: suppId
                            }
                        });
                    }}
                    className={"search-input-comp-local"}
                >
                    <p>搜本店</p>
                </div>
            );
        }
        return (
            <div
                onClick={showHighLevel ? hideHighLevel : clickHighLevel}
                className={
                    showHighLevel
                        ? "search-comps-high-level-choose"
                        : "search-comps-high-level"
                }
            >
                <p
                    className={
                        showHighLevel
                            ? "search-comps-high-level-p1"
                            : "search-comps-high-level-p"
                    }
                >
                    {showHighLevel ? "收起" : "高级搜索"}
                </p>
            </div>
        );
    }
}
